package com.hoyue.servlet;

import com.hoyue.bean.Info;
import com.hoyue.service.InfoService;
import com.hoyue.utils.Page;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Hoyue_network1
 * @version 1.0
 * Creat by 2018/8/24 16:51
 */
@WebServlet("/InfoServlet")
public class InfoServlet extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("method");//获取方法名
		if (name == null || name.isEmpty()) {
			throw new RuntimeException("没有传递method参数,请给出你想调用的方法");
		}
		Class c = this.getClass();//获得当前类的Class对象
		Method method = null;
		try {
			//获得Method对象
			method = getClass().getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("没有找到" + name + "方法，请检查该方法是否存在");
		}

		try {
			method.invoke(this, request, response);//反射调用方法
		} catch (Exception e) {
			System.out.println("你调用的方法" + name + ",内部发生了异常");
			throw new RuntimeException(e);
		}

	}

	InfoService infoService = new InfoService();

	protected void getInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		double randomNum = Math.random();
		request.setAttribute("randomNum", randomNum);

        List<Info> info = infoService.getAllInfo();

		request.setAttribute("info", info);

		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	protected void adminGetInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		double randomNum = Math.random();
		request.setAttribute("randomNum", randomNum);
		String flag = request.getParameter("flag");

		String Pexpand = request.getParameter("Pexpand");

		if(Pexpand == null || Pexpand.equals("true")) {
			request.setAttribute("Pexpand","true");
			request.setAttribute("Nexpand","false");
		} else {

			request.setAttribute("Pexpand","false");
			request.setAttribute("Nexpand","true");
		}

		String Pclass1 = request.getParameter("Pclass1");
		if(Pclass1 == null || Pclass1.equals("active")) {
			request.setAttribute("Pclass1","active");
			request.setAttribute("Nclass1","");
		} else {
			request.setAttribute("Pclass1","");
			request.setAttribute("Nclass1","active");
		}

		String Pclass2 = request.getParameter("Pclass2");
		if(Pclass2 == null || Pclass2.equals("active in")) {
			request.setAttribute("Pclass2","active in");
			request.setAttribute("Nclass2","");
		} else {
			request.setAttribute("Pclass2","");
			request.setAttribute("Nclass2","active in");
		}


		/* ----------有图资讯---------- */
		String page1 = request.getParameter("page1");

		if(page1 == null || page1.equals("")){
			page1 = "1";
		}
		int picPage = Integer.parseInt(page1);

		Page<Info> picInfo = infoService.getPicPage(picPage);

		request.setAttribute("picInfo",picInfo);

		/* ----------无图资讯---------- */
		String page2 = request.getParameter("page2");
		if(page2 == null || page2.equals("")) {
			page2 = "1";
		}
		int noPicPage = Integer.parseInt(page2);

		Page<Info> noPicInfo = infoService.getNoPicPage(noPicPage);
		request.setAttribute("noPicInfo",noPicInfo);

		request.getRequestDispatcher("/WEB-INF/admin/information.jsp").forward(request, response);
	}


	protected void addInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Info info = new Info();
		info.setPicture(false);

		Map<String, Object> map = new HashMap<>();

		DiskFileItemFactory factory = new DiskFileItemFactory();

		ServletFileUpload sfu = new ServletFileUpload(factory);

		try {
			List<FileItem> items = sfu.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String fileName = item.getFieldName();
					String fileValue = item.getString("UTF-8");
					if (fileValue.equals("yes")) {
						info.setPicture(true);
					}
					map.put(fileName, fileValue);
				} else {
					if (info.getPicture() == false) {
						map.put("address", "");
						continue;
					}
					String name = System.currentTimeMillis() + ".jpg";
					String photoFolder = this.getServletContext().getRealPath("page/images/information");

					InputStream inputStream = item.getInputStream();

					OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);

					IOUtils.copy(inputStream, outputStream);

					inputStream.close();
					outputStream.close();
					item.delete();

					map.put("address", "page/images/information/" + name);
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		try {
			BeanUtils.populate(info, map);
		} catch (Exception e) {
			e.printStackTrace();
		}

		infoService.addInfo(info);

		request.getRequestDispatcher(request.getContextPath() + "/InfoServlet?method=adminGetInfo").forward(request, response);
	}

	protected void deleteInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

        int id = Integer.parseInt(request.getParameter("id"));
        //查找地址
        String picPath = infoService.getAddressById(id);
        String address = this.getServletContext().getRealPath(picPath);

		File file = new File(address);
		if(file.exists()) {
			file.delete();
		}

		infoService.delete(id);

		request.getRequestDispatcher(request.getContextPath() + "/InfoServlet?method=adminGetInfo").forward(request, response);
	}

	protected void updateInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		Info info = new Info();
		info.setId(id);
		info.setPicture(false);
		int flag = 0;


		Map<String, Object> map = new HashMap<>();

		DiskFileItemFactory factory = new DiskFileItemFactory();

		ServletFileUpload sfu = new ServletFileUpload(factory);

		try {
			List<FileItem> items = sfu.parseRequest(request);

			for (FileItem item : items) {
				if (item.isFormField()) {
					String fileName = item.getFieldName();
					String fileValue = item.getString("UTF-8");
					map.put(fileName, fileValue);
				} else {
					flag = 1;
					info.setPicture(true);
					String address = infoService.getAddressById(id);
					String name = address.substring(address.lastIndexOf("/") + 1);

					if(item.getName().equals("")) {
						map.put("address",address);
						continue;
					}

					String photoFolder = this.getServletContext().getRealPath("page/images/information");

					InputStream inputStream = item.getInputStream();
					OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);

					IOUtils.copy(inputStream,outputStream);

					inputStream.close();
					outputStream.close();
					item.delete();

					map.put("address",address);
				}
			}
			if(flag == 0) {
				info.setAddress("");
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		try {
			BeanUtils.populate(info, map);
		} catch (Exception  e) {
			e.printStackTrace();
		}

		infoService.updateInfo(info);
		response.sendRedirect(request.getContextPath() + "/InfoServlet?method=adminGetInfo");
	}

	protected void searchInfo(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
		String search = request.getParameter("search");
		String Pexpand = request.getParameter("Pexpand");

		if(Pexpand == null || Pexpand.equals("true")) {
			request.setAttribute("Pexpand","true");
			request.setAttribute("Nexpand","false");
		} else {

			request.setAttribute("Pexpand","false");
			request.setAttribute("Nexpand","true");
		}

		String Pclass1 = request.getParameter("Pclass1");
		if(Pclass1 == null || Pclass1.equals("active")) {
			request.setAttribute("Pclass1","active");
			request.setAttribute("Nclass1","");
		} else {
			request.setAttribute("Pclass1","");
			request.setAttribute("Nclass1","active");
		}

		String Pclass2 = request.getParameter("Pclass2");
		if(Pclass2 == null || Pclass2.equals("active in")) {
			request.setAttribute("Pclass2","active in");
			request.setAttribute("Nclass2","");
		} else {
			request.setAttribute("Pclass2","");
			request.setAttribute("Nclass2","active in");
		}

        List<Info> info = infoService.searchInfo(search);
        request.setAttribute("info", info);

        request.getRequestDispatcher("/WEB-INF/admin/information.jsp").forward(request, response);
    }
}
